import { defineStore } from 'pinia'
import { RouteRecordRaw } from 'vue-router'
import { accountDetailGetApi } from "@/api/login"
import { ElMessage } from "element-plus"
import Center from '@/layout/center/center.vue'
import Layout from '@/layout/Index.vue'
// {
//   // 配置404页面
//   path: '/:catchAll(.*)',
//   name: '404',
//   component: () => import('@/view/error/404.vue'),
// }

// 这个引入 只能通过单个操作
const modules = import.meta.glob('../view/**/*.vue')

// 三级自定义

export interface MenuState {
  menuList: any,
  childrenMenu: any[],
  saveMenuList: any[],
  permissionBtn: any[],
  sensitive: any[],
  customFatherMenu: any[],
  customSonMenu: any[],
  isCollapse: boolean,
  hideAside: boolean
}
// 定义store
export const menuStore = defineStore('menuStoreId', {
  state: (): MenuState => {
    return {
      childrenMenu: [],
      menuList: [],
      saveMenuList: [],
      permissionBtn: [],
      sensitive: [],
      customFatherMenu: ['/associateMember/tcl', '/associateMember/jxw', '/associateMember/hht', '/associateMember/yk', '/associateMember/ng', '/associateMember/keep',
        '/associateMember/clhk', '/associateMember/xmly', '/rights_manage/scheme_equity'],
      customSonMenu: [],// bug->刷新数据保存 2 点击做什么事情
      isCollapse: false,
      hideAside: true
    }
  },
  actions: {
    getMenuList(router: any) {
      return new Promise((resolve, reject) => {
        //  数据
        accountDetailGetApi().then(async res => {
          let accessedRoutes;
          if (res.code == 20000) {
            //动态生成路由
            if (res.data.length <= 0) {
              ElMessage({
                type: "warning",
                message: "暂无菜单权限 请联系管理员授权，请联系管理员"
              })
              router.push({ path: "/login" })
              sessionStorage.clear()
              return
            }
            // 处理数据

            // 过滤掉 个人中心
            const delArr = ['个人中心', '敏感数据查看']
            this.saveMenuList = res.data.filter((it: any) => {
              return !delArr.includes(it.title)
            })
            this.saveMenuList = this.filterAuthorities(this.saveMenuList)

            // 做一个没有 

            this.saveMenuList.unshift({
              code: "USER_MAN",
              icon: "board",
              parentAuthorityCode: "-1",
              path: "/",
              redirect: "/personalCenter/echart",
              title: "用户控制台", type: -1,
              // isLink: 'http://119.45.226.216:8888/xxl-job-admin/',
              // isHide: false,
              // isIframe: false,
              authority: [
                {
                  code: "USER_MAN_ECHART",
                  icon: "board",
                  parentAuthorityCode: "-1",
                  path: "/personalCenter/echart",
                  title: "用户控制台",
                  type: 1,
                  authority: []
                },
              ]
            })
            const ress = this.newhandleData(this.saveMenuList)
            accessedRoutes = filterAsyncRoutes(ress, router);
            //设置到menuList
            this.menuList = []
            this.menuList = accessedRoutes
            console.log(this.menuList);

          }
          resolve(accessedRoutes);
        }).catch((error: any) => {
          reject(error)
        })
      })
    },
    filterAuthorities(authorities: any) {
      // 妈的 我的type = 99 的数据怎么不见了
      return authorities.filter((authority: any) => {
        if (authority.type === 1) {
          // 检查子节点中是否有 title 包含“分页”的字符
          const hasPagination = authority.authority.some((subAuthority: any) =>
            subAuthority.title.includes('分页')
          );
          if (hasPagination) {
            // 如果有符合条件的子节点，递归处理子节点
            authority.authority =authority.authority
            return true;
          } else {
            // 如果没有符合条件的子节点，移除该节点
            return false;
          }
        } else {
          // 递归处理子节点
          authority.authority = this.filterAuthorities(authority.authority);
          // 如果子节点为空或为空数组，移除该节点
          return authority.authority.length > 0;
        }
      });
    },
    newhandleData(data: any) {
      const res: any = []
      data && data.map((item: any, index: number) => {
        if (item.type == 3) {
          this.sensitive = []
          this.sensitive.push(item)
          return
        }
        const tmp = { ...item }
        tmp.children = tmp.authority
        tmp.name = tmp.title + index
        delete tmp.authority;
        tmp.meta = {
          title: tmp.title,
          icon: tmp.icon,
          // 添加一个参数 用来判断 isIframe,
          isIframe: false,
          isLink:tmp.isLink?tmp.isLink:'',
        }
        // 在处理递归 没有长度的 怎么办 
        if (tmp.type == -1 && tmp.parentAuthorityCode == -1) {
          tmp.component = Layout
        }
        if (tmp.children?.length > 0) {
          // 数据怎么玩
          tmp.permission = tmp.children.filter((it: any) => it.type == 99)

          // 需要添加hidden
          if (tmp.type == 1 && tmp.parentAuthorityCode != -1) {
            tmp.component = modules[`../view${tmp.path}/index.vue`]
          }
          // 这个地方需要判断
          if (tmp.type == 2 && tmp.parentAuthorityCode != -1) {

            // 
            tmp.component = this.customFatherMenu.includes(tmp.path)
              ? modules[`../view${tmp.path}/index.vue`]
              : Center;

            if (this.customFatherMenu.includes(tmp.path)) {
              tmp.customChild = tmp.children
              tmp.children = []
            }
          }
          // 递归
          // tmp.hidden = true
          // 联合会员 后期多个会员 就是
          if (tmp.children && tmp.children.length > 0) {
            tmp.children = this.newhandleData(tmp.children.filter((it: any) => it.type == 1 || it.type == 2))
          }
          if (tmp.customChild && tmp.customChild.length > 0) {
            tmp.customChild = this.newhandleData(tmp.customChild.filter((it: any) => it.type == 1 || it.type == 2))
          }

        } else if (tmp.type == 1) {
          tmp.component = modules[`../view${tmp.path}/index.vue`]
        }

        if (tmp.children && tmp.children.length === 0) {
          delete tmp.children;
        }
        res.push(tmp)
      })
      return res
    },
    /* 自定义菜单 */
    saveCustomMenu(data: any) {

    },
    setChildrenMenu(list: any[]) {

      this.childrenMenu = list
    },
    filterPermission(path: string | number, childrenMenu: any) {

      childrenMenu.some((item: any) => {
        if (item.path == path) {
          if (item.permission && item.permission.length > 0) {
            this.permissionBtn = item.permission.map(it => {
              return {
                code: it.code,
                title: it.title
              }
            })
          }
          return true
        }
        if (item?.children && item.children.length > 0) {
          this.filterPermission(path, item.children)
        }
      })
    },
    flashRouter(router: any) {
      let accessedRoutes;
      if (this.saveMenuList.length <= 0) {
        ElMessage({
          type: "warning",
          message: "暂无菜单权限 请联系管理员授权，请联系管理员"
        })
        router.push({ path: "/login" })
        sessionStorage.clear()
        return
      }
      const ress = this.newhandleData(this.saveMenuList)

      accessedRoutes = filterAsyncRoutes(ress, router);
      //设置到menuList
      this.menuList = []
      this.menuList = accessedRoutes
    },
    clearStrore() {
      this.childrenMenu = []
      this.menuList = []
      this.saveMenuList = []
      this.permissionBtn = []
      this.sensitive = []
    },
    async setNewMenuList(menu: any) {

    },
  },
  getters: {
  },
  persist: {
    //默认名称为当前store唯一标识 这里即home
    key: 'menuStoreId',
    //默认localStorage 本地储存 
    //这里建议临时储存sessionStorage 也可写成window.sessionStorage
    storage: sessionStorage,
    //默认当前store里的所有变量都持久化
    paths: ['saveMenuList', 'sensitive', 'permissionBtn', 'customSonMenu', 'isCollapse']
  }

})

// 什么问题 
export function filterAsyncRoutes(routes: any[], router: any) {

  const res: Array<any> = []
  routes && routes.map((route: any) => {
    const tmp = { ...route }
    if (tmp.children && tmp.children.length > 0) {

      tmp.redirect = tmp.children[0].path
      tmp.children = filterAsyncRoutes(tmp.children, router)
    }

    router.addRoute(tmp)
    res.push(tmp)
  })
  return res
}